package com.mlnx.mptp.serial;


import com.mlnx.common.utils.MyLog;

import java.io.IOException;
import java.io.InputStream;


public class ReciveDataRunnable implements Runnable {

    MyLog log = MyLog.getLog(getClass());

    private InputStream recvStream;
    private boolean isRun;

    private byte[] buff = new byte[3000];

    private IReciver revicer;

    public ReciveDataRunnable(InputStream recvStream, IReciver revicer) {
        super();
        this.recvStream = recvStream;
        this.revicer = revicer;
    }

    @Override
    public void run() {

        isRun = true;
        while (isRun) {
            try {
                if (recvStream.available() > 0) {
                    int len = recvStream.read(buff);
                    if (revicer != null) {
                        revicer.recive(buff, len);
                    }
                }
            } catch (IOException e) {
                log.error("串口接收数据错误", e);
            }

            synchronized (recvStream) {
                try {
                    recvStream.wait(10);
                } catch (InterruptedException e) {
                    log.error("", e);
                }
            }
        }
    }

    public void stop() {
        isRun = false;

        synchronized (recvStream) {
            recvStream.notify();
        }
    }

}
